<?php

namespace App\Admin\Actions\ShopOrderReturn;

use App\Library\Logic\OperateLogLogic;
use App\Library\Service\Payment\WechatService;
use App\Models\ShopOrderReturnModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Yansongda\Artful\Exception\ContainerException;
use Yansongda\Artful\Exception\InvalidParamsException;
use Yansongda\Artful\Exception\ServiceNotFoundException;

class ShopOrderReturnPartOnlyAction extends ShopOrderReturnAuction
{
    public $name = '部分退款';//仅退款

    /**
     * handle
     * @param ShopOrderReturnModel $model
     * @param Request $request
     * @return Response
     * @throws ContainerException
     * @throws InvalidParamsException
     * @throws ServiceNotFoundException
     */
    public function handle(ShopOrderReturnModel $model, Request $request): Response
    {
        if ((int)$model->or_type !== 2) return $this->response()->error('参数错误')->refresh();
        $this->saveModel($model);
        $model->or_real_price = $request->amount;
        $model->or_note = $request->reason;
        $model->save();
        payLog(WechatService::refund($model)->toArray());
        OperateLogLogic::add(Admin::user()->user_id, 'admin.orderReturn.partOnly');
        self::salesHandle($model, '已同意');
        return $this->response()->success('操作成功')->refresh();
    }

    /**
     * handle
     * @param ShopOrderReturnModel $model
     * @return void
     */
    public function form(ShopOrderReturnModel $model): void
    {
        $ensurePrice = $model->or_ensure_price * 1;
        $this->text('amount', '退款金额')->attribute('maxlength', 10)->required();
        $this->text('reason', '退款原因')->attribute('maxlength', 255)
            ->help("用户申请金额 ￥$model->or_real_price 订单保证金：￥{$ensurePrice}（发货后保证金不退）");
    }
}
